package cn.hl.hm.util.chinapay;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chinapay.secss.SecssUtil;
import com.chinapay.util.log.MonitorLogger;

import net.sf.json.JSONObject;

/**
 * 异cppaydemo.util.处理类
 * 
 * @author sun.jun
 */
public class CardValidResultServlet extends HttpServlet {
	private static final MonitorLogger logger = MonitorLogger.getLogger(CardValidResultServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -1075416647383366061L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		long beginTime = System.currentTimeMillis();
		try {
			logger.info("开始接收前台认证后台通知，并解析...");
			
			// 验签
			Map<String, String> resultMap = new HashMap<String, String>();
			for (Enumeration en = request.getParameterNames(); en.hasMoreElements();) {
				String temp = (String)en.nextElement();
				resultMap.put(temp, request.getParameter(temp));
			}
			logger.info("接收到的报文"+new UnionValidServlet().getURLParam(resultMap, false, null));
			// 初始化
			SecssUtil secssUtil = new SecssUtil();
			
			String merNo = (String) resultMap.get("merNo");
			String instId = (String) resultMap.get("instId");
			String fileKey = StringUtil.isNotEmpty(instId)?instId:merNo;
			secssUtil.init(PathUtil.getValue("security_"+fileKey+"_url"));
			
			resultMap.remove("merNo");
			resultMap.remove("instId");
			
			//摘要加密SHA512
			Map<String, String> verifyMap = new HashMap<String, String>();
			String encRespDataStr = resultMap.get("respData");
			encRespDataStr = Encryptor.encode(encRespDataStr, "SHA-512");
			verifyMap.put("respData", encRespDataStr);
			verifyMap.put("signature", resultMap.get("signature"));
			
			secssUtil.verify(verifyMap);
			
			if(!"00".equals(secssUtil.getErrCode())){
				logger.info("验签失败");
			} else {
				logger.info("验签成功");
			}
			
			String respStrDecode = new String(Base64.decode(resultMap.get("respData").toCharArray()), "UTF-8");
			JSONObject jsonRes = JSONObject.fromObject(respStrDecode);
			Iterator it = jsonRes.keys();
			Map<String, String> respmsgMap = new HashMap<String,String>();
			while (it.hasNext()) {
				String key2 = String.valueOf(it.next());
	            String value = (String) jsonRes.get(key2);
	            
	            // 解密
	            if ("sensData".equals(key2)) {
	            	secssUtil.decryptData(value);
	            	if(!"00".equals(secssUtil.getErrCode())){
	            		return;
	            	}
	            	JSONObject jsonSensData = JSONObject.fromObject(secssUtil.getDecValue());
	            	Iterator sensDataIt = jsonSensData.keys();
	            	while (sensDataIt.hasNext()){
	            		String sensDataKey = String.valueOf(sensDataIt.next());
	    	            String sensDataValue = (String) jsonSensData.get(sensDataKey);
	    	            respmsgMap.put(sensDataKey, sensDataValue);
	            	}
	            } else {
	            	respmsgMap.put(key2, value);
	            }
			}
			
			String respMsg = new UnionValidServlet().getURLParam(respmsgMap, false, null);
			logger.info("解析应答报文后的报文respMsg=["+respMsg+"]");
			
			return;
			
		} catch (Exception e) {
			logger.error("系统异常!");
			logger.fatal((Throwable) e);
		}finally{
			logger.info("总耗时:"+(System.currentTimeMillis()-beginTime)+"毫秒");
		}
	}

}
